package com.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.Subject;
import com.edu.entity.excel.SubjectData;
import com.edu.entity.subject.OneSubject;
import com.edu.entity.subject.TwoSubject;
import com.edu.listener.SubjectExcelListener;
import com.edu.mapper.SubjectMapper;
import com.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-06-16
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

	//添加课程分类
	@Override
	public void saveSubject(MultipartFile file, SubjectService subjectService) {
		try {
			InputStream in = file.getInputStream();
			EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<OneSubject> getAllOneTwoSubject() {
		//1查询所有一级分类 parent_id = 0
		QueryWrapper<Subject> wrapperOne = new QueryWrapper<>();
		wrapperOne.eq("parent_id","0");
		List<Subject> onelist = baseMapper.selectList(wrapperOne);

		//2查询所有二级分类 parent_id != 0
		QueryWrapper<Subject> wrapperTwo = new QueryWrapper<>();
		wrapperTwo.ne("parent_id","0");
		List<Subject> twolist = baseMapper.selectList(wrapperTwo);

		//创建list集合，用于存储最终封装数据
		List<OneSubject> finalList = new ArrayList<>();

		//3封装一级分类
		for (int i = 0; i < onelist.size(); i++) {
			Subject subject = onelist.get(i);
			OneSubject oneSubject = new OneSubject();
			//法一：
//			oneSubject.setId(subject.getId());
//			oneSubject.setTitle(subject.getTitle());
			//法二：工具类
			BeanUtils.copyProperties(subject,oneSubject);
			finalList.add(oneSubject);

			ArrayList<TwoSubject> twoFinalList = new ArrayList<>();
			//遍历二级分类list集合
			for (int m = 0; m < twolist.size(); m++) {
				Subject tSubject = twolist.get(m);
				if (tSubject.getParentId().equals(subject.getId())){
					TwoSubject twoSubject = new TwoSubject();
					BeanUtils.copyProperties(tSubject,twoSubject);
					twoFinalList.add(twoSubject);
				}
			}

			oneSubject.setChildren(twoFinalList);

		}

		return finalList;
	}


}
